const dbPool = require('../../conf/db.js')
const template = require('../../conf/template.js')

/* 获取商品分类 */
function getCommodityType(req, res, next) {
	let sql = 'select * from commodity_type'
	dbPool.execute(sql, (err, rows) => {
		if (!err) {
			res.send(template(200, rows, '成功'))
		} else {
			res.send(template(199, [], '失败'))
		}
	})
}

/* 设置商品分类 */
function setCommodityType(req, res, next) {
	let sql =
		`insert into commodity_type (commodity_type_title,commodity_type_img) values('${req.body.commodity_type_title}','${req.body.commodity_type_img}')`
	let sql2 = `select * from commodity_type where commodity_type_title = '${req.body.commodity_type_title}'`
	dbPool.query(sql2, (err, rows) => {
		if (rows.length > 0) {
			res.send(template(199, [], '失败,存在同名分类'))
		} else {
			dbPool.execute(sql, (err, rows) => {
				if (!err) {
					res.send(template(200, [], '成功'))
				} else {
					res.send(template(199, rows, '失败'))
				}
			})
		}
	})
}

/* 添加商品 */
function addGoods(req, res, next) {
	let sql =
		`insert into goods_list (commodity_type_id,goods_title,goods_price,goods_description) values('${req.body.commodity_type_id}','${req.body.goods_title}','${req.body.goods_price}','${req.body.goods_description}')`
	let sql2 = `select * from commodity_type where commodity_type_id = '${req.body.commodity_type_id}'`
	dbPool.query(sql2, (err, rows) => {
		if (rows.length == 0) {
			res.send(template(199, [], '失败,不存在该商品分类'))
		} else {
			dbPool.execute(sql, (err, rows) => {
				if (!err) {
					res.send(template(200, [], '成功'))
				} else {
					res.send(template(199, rows, '失败'))
				}
			})
		}
	})
}

/* 删除商品 */
function deleteGoods(req, res, next) {
	let sql =
		`delete from goods_list where goods_id =  '${req.body.goods_id}'`
	let sql2 = `select * from goods_list where goods_id = '${req.body.goods_id}'`
	dbPool.query(sql2, (err, rows) => {
		if (rows.length == 0) {
			res.send(template(199, [], '失败,不存在该商品'))
		} else {
			dbPool.execute(sql, (err, rows) => {
				if (!err) {
					res.send(template(200, [], '成功'))
				} else {
					res.send(template(199, rows, '失败'))
				}
			})
		}
	})
}

/* 获取商品列表 */
function getGoodsList(req, res, next) {
	let commodity_type_id = req.body.commodity_type_id
	let sql = ''
	if (commodity_type_id == 0) {
		sql = `select * from goods_list limit ${req.body.page -1},${req.body.pagesize}`
	} else {
		sql =
			`select * from goods_list where commodity_type_id = '${commodity_type_id}' limit ${req.body.page -1},${req.body.pagesize}`
	}
	dbPool.execute(sql, (err, rows) => {
		res.send(template(200, {
			list: rows
		}, '成功', {
			'page': Number(req.body.page),
			'pagesize': Number(req.body.pagesize)
		}))
	})
}

module.exports = {
	getCommodityType,
	setCommodityType,
	addGoods,
	deleteGoods,
	getGoodsList
}
